package pers.w.chaptertalk.ui;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import pers.w.chaptertalk.R;
import pers.w.chaptertalk.funs.BookInfo;
import pers.w.chaptertalk.funs.Fun;
import pers.w.chaptertalk.funs.WebBmpThread;


public class ListViewAdapter extends BaseAdapter {


    private Activity activity;// Context context;
    private List<BookInfo> listItems;
    private LayoutInflater listContainer;
    private List<WebBmpThread> thread_list;
    private String buttonText=". . .";
    public static final class ListItemView {
        public ImageView image1;
        public TextView name;
        public TextView author;
        public TextView lastUpTime;
        public TextView button;
        public BookInfo bookInfo;
    }

    private HashMap<Integer, ListItemView> listItemViewHashMap = new HashMap<>();
    // private HashMap<Integer, Bitmap> bitmaps;


    public void setButtonText(String buttonText) {
        this.buttonText = buttonText;
    }

    public ListViewAdapter(final Context context, final Activity activity, final List<BookInfo> listItems) {
        //this.context = context;
        listContainer = LayoutInflater.from(context);   //创建视图容器并设置上下文
        this.activity = activity;
        this.listItems = listItems;

        //this.bitmaps = new HashMap<>();
        thread_list = new ArrayList<>();
    }

    public void startBmpThreads() {
        startBmpThreads(Math.min(listItems.size(), 2));
    }
    public void startBmpThreads(int threads) {
        // final Activity activity = Fun.findActivity(context);

        final int step = threads;//判断创建多少个线程，按步进每个线程分别从i开始读取图片
        for (int i = 0; i < step; i++) {
            WebBmpThread thread = new WebBmpThread(listItems, i, step) {
                @Override
                public void runOnUiThread(final int position) {
                    assert activity != null;
                    activity.runOnUiThread(() -> {
                        ListItemView listItemView = listItemViewHashMap.get(position);
                        if (null != listItemView && null != listItemView.image1)
                            listItemView.image1.setImageBitmap(listItems.get(position).getImage_bmp());
                    });
                }
            };
            thread_list.add(thread);
            thread.start();
        }
    }

    @Override
    public int getCount() {
        return listItems.size();
    }

    @Override
    public BookInfo getItem(int position) {
        return listItems.get(position);
    }

    //从bitmaps里面得到图片，可能为null
    public Bitmap getItemBitmap(int position) {
        return listItems.get(position).getImage_bmp();
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ListItemView listItemView;
        if (Fun.isDebug()) Log.d("listview", "准备绘制item" + position);
        BookInfo bookInfo = listItems.get(position);
        if (bookInfo.getID() > 0) bookInfo.readBmp();//有id，说明被添加过，直接读取本地图片
        if (null == convertView) {
            if (Fun.isDebug()) Log.d("listview", "创建item" + position);

            listItemView = new ListItemView();
            convertView = listContainer.inflate(R.layout.list_item, null);
            convertView.setTag(listItemView);

            listItemView.image1 = convertView.findViewById(R.id.image1);
            listItemView.name = convertView.findViewById(R.id.text1);
            listItemView.author = convertView.findViewById(R.id.text2);
            listItemView.lastUpTime = convertView.findViewById(R.id.text3);
            listItemView.button = convertView.findViewById(R.id.button1);
            listItemView.button.setTag(listItemView);
            listItemView.button.setText(buttonText);
            listItemView.button.setOnClickListener(v -> on3dotClick((ListItemView) v.getTag()));

            listItemView.bookInfo = bookInfo;
            listItemViewHashMap.put(position, listItemView);
        } else {
            listItemView = (ListItemView) convertView.getTag();
        }

        //获得这个view要绘制的info
        //从bitmaps读取要绘制到imageview的图片，如果没用找到，调用线程从web获取
        Bitmap bmp = listItems.get(position).getImage_bmp();
        if (null == bmp) {
            listItemView.image1.setImageResource(R.drawable.loading);
        } else {
            listItemView.image1.setImageBitmap(bmp);
        }

        listItemView.name.setText(bookInfo.getFieldValue(R.string.info_name));
        listItemView.author.setText(bookInfo.getFieldValue(R.string.info_author));
        listItemView.lastUpTime.setText(bookInfo.getFieldValue(R.string.info_lastUpdateTime));
        listItemView.bookInfo = bookInfo;
        return convertView;
    }

    public void on3dotClick(ListItemView listItemView) {
    }


    public void stopThreads() {
        for (WebBmpThread thread : thread_list) {
            if (null != thread) thread.setStop(true);
        }
    }

    @Override
    protected void finalize() throws Throwable {
        stopThreads();
        super.finalize();
    }
}